package com.oauth.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.OAuth2ClientProperties;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author ytj
 * @date 2021/12/10
 */
@RestController
@RequestMapping("/")
public class CallBackController {
    @Resource
    private OAuth2ClientProperties oAuth2ClientProperties;

    @Value("${security.oauth2.access-token-uri}")
    private String accessToken;

    @GetMapping("/callback")
    public OAuth2AccessToken callback(String code){
        AuthorizationCodeResourceDetails authorizationCodeResourceDetails=new AuthorizationCodeResourceDetails();
        authorizationCodeResourceDetails.setAccessTokenUri(accessToken);
        authorizationCodeResourceDetails.setClientId(oAuth2ClientProperties.getClientId());
        authorizationCodeResourceDetails.setClientSecret(oAuth2ClientProperties.getClientSecret());
        OAuth2RestTemplate restTemplate=new OAuth2RestTemplate(authorizationCodeResourceDetails);
        restTemplate.getOAuth2ClientContext().getAccessTokenRequest().setAuthorizationCode(code);
        restTemplate.getOAuth2ClientContext().getAccessTokenRequest().setPreservedState("http://127.0.0.1:6064/callback");
        restTemplate.setAccessTokenProvider(new AuthorizationCodeAccessTokenProvider());
        return restTemplate.getAccessToken();
    }
}
